<?php

namespace App\Models;

use Cache;

class Service extends BaseModel
{
    protected $table = "service";

    const DB_SERVICE_DATA = 'DB_SERVICE_DATA';

    protected $rules = [
        'name' => 'required|between:1,33',
        'group_id' => 'required|unique:service',
        'base_price' => 'required|numeric:6',
        'time' => 'required',
    ];

    protected $message = [
        'name.required' => '套餐名称必须填写',
        'name.between' => '名称不能超过33个字',
        'group_id.required' => '用户组必须选择',
        'group_id.unique' => '该权限组已有套餐，请勿重复添加',
        'base_price.required' => '基础服务费必须填写',
        'base_price.numeric' => '基础服务费必须是数字',
        'time.required' => '服务期限必须选择',
    ];

    public function group()
    {
        return $this->hasOne('App\Models\Group', 'group_id', 'id');
    }


    public function getInfo($adminId, $shopId = 0)
    {
        $authGroupAccess = new AuthGroupAccess();
        $accessInfo = $authGroupAccess->_getOne(['aid' => $adminId]);
        if (!$accessInfo) {
            $accessInfo['group_id'] = 3;
        }
        $info = $this->getCache();
        $serviceInfo = $info[$accessInfo['group_id']];
        $serviceInfo['money'] = $serviceInfo['base_price'];
        if ($shopId) {
            $shop = new Shop();
            $shopInfo = $shop->_redisGetOneBySid($shopId);
            if (!$shopInfo) {
                $this->error = '非法操作';
                return false;
            }
            $serviceInfo['money'] = $shopInfo['service_price'];
            if ($serviceInfo['money'] < 1 && is_numeric($serviceInfo['shop_price'])) {
                $serviceInfo['money'] = $serviceInfo['shop_price'];
            }
            if ($serviceInfo['data'] && $serviceInfo['money'] < 1 && ($shopInfo['service_price'] < 1)) {
                $num = $shop->_count(['admin_id' => $adminId]);
                if (!$num) {
                    $this->error = '商户没有开店';
                    return false;
                }
                $money = 0;
                foreach ($serviceInfo['data'] as $v) {
                    if (!is_array($v[0])) {
                        $this->error = '套餐数据不合法';
                        return false;
                    }
                    $min = $v[0][0];
                    $max = $v[0][1];
                    if ($num >= $min && $num <= $max) {
                        $money = $v[1];
                    }
                }
                if (!$money) {
                    if ($num == 1) {
                        $money = $serviceInfo['data'][0][1];
                    } else {
                        $money = $serviceInfo['data'][count($serviceInfo['data'])][1];
                    }
                }
                if (!$money) {
                    $this->error = '计算订单金额错误';
                    return false;
                }
                $serviceInfo['money'] = $money;
            }
        }
        return $serviceInfo;
    }

    public function addOrUpdate()
    {
        $data['name'] = trim(request('name'));
        $data['group_id'] = request('group_id');
        $data['time'] = trim(request('time'));
        $data['base_price'] = intval(trim(request('base_price')));
        $data['shop_price'] = trim(request('shop_price', 0));
        if (is_numeric($data['shop_price'])) {
            $data['shop_price'] = intval($data['shop_price']);
        }
        if (strpos($data['shop_price'], ':')) {
            $arr = explode("\r\n", $data['shop_price']);
            $tem = [];
            if (is_array($arr)) {
                foreach ($arr as $v) {
                    if ($v) {
                        $tem[] = $v;
                    }
                }
            }
            $data['shop_price_data'] = json_encode($tem);
            $str = str_replace("\r\n", "\n", $data['shop_price']);
            $data['shop_price'] = strip_tags($str, "\n");
        }
        if (request('id')) {
            $data['id'] = trim(request('id'));
            $this->rules['group_id'] .= ',id,' . $data['id']; //唯一字段验证,在更新时排除当前id
        }
        if (!$this->_validate($data)) {
            return false;
        }
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '操作失败，请稍后再试!';
            return false;
        }
        $this->delCache();
        return '保存成功！';
    }

    public function getCache()
    {
        $data = Cache::get(self::DB_SERVICE_DATA);
        if (!$data) {
            $res = $this->_getList();
            if ($res) {
                $res = $res->toArray();
                $data = [];
                foreach ($res as $v) {
                    $data[$v['group_id']] = $v;
                    if ($v['shop_price_data']) {
                        $arr = json_decode($v['shop_price_data']);
                        foreach ($arr as $m) {
                            if (strpos($m, ':')) {
                                $tem = explode(':', $m);
                                $data[$v['group_id']]['data'][] = [explode(',', $tem[0]), $tem[1]];
                            }
                        }
                    } else {
                        $data[$v['group_id']]['data'] = $v['shop_price'];
                    }
                }
            }
            Cache::forever(self::DB_SERVICE_DATA, $data);
        }
        return $data;
    }


    public function delCache()
    {
        Cache::forget(self::DB_SERVICE_DATA);
    }


}
